package cn.le.springAnnotationCustomize.annotationUtil;

import org.eclipse.core.runtime.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.Errors;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by admin on 2017/3/30.
 */

public abstract class AbastractCustomerValidatorRule implements CustomerValidatorRule{

    @Override
    public abstract boolean support(Annotation annotation);

    @Override
    public void valid(Annotation annotation, final Object target, final Field field, final Errors errors) throws Exception {
        //为空验证
        preHandle(annotation, target, field, errors);
        //PropertyDescriptor获取描述的Java bean通过一对存储器方法导出的一个属性
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(target.getClass(),
                field.getName());
        // 获得应该用于读取属性值的方法信息对象
        //method提供了关于类或接口上单独某个方法(以及如何访问该方法)的信息
        //所反映的方法可能是类方法或者实例方法(包括抽象方法)
        Method reader = propertyDescriptor.getReadMethod();
        //对带有指定参数的指定对象调用此method对象表示的底层方法,其返回的是Method对象方法的参数值
        Object property = reader.invoke(target);
        validProperty(annotation, property, new PostHandler() {
            public void postHanle(String errorCode, String message) {
                errors.rejectValue(field.getName(), errorCode, message);
            }
        });

    }
    public static interface PostHandler{
        public void postHanle(String errorCode,String message);
    }
    private void preHandle(Annotation annotation, Object object, Field field, Errors errors)
    {
        Assert.isNotNull(object);
        Assert.isNotNull(annotation);
        Assert.isNotNull(errors);
        Assert.isNotNull(field);
    }
    public abstract void validProperty(Annotation annotation, Object property,PostHandler postHandler);
}
